//
//  ZKingAddressBookViewController.m
//  ZKingAddressBook
//
//  Created by zkingsoft on 15/12/24.
//  Copyright (c) 2015年 zkingsoft. All rights reserved.
//

#import "ZKingAddressBookViewController.h"

#import "AddressBookPeopleModel.h"
#import "AddressBookView.h"
#import "AddressBookTableViewCell.h"
#import "AddressBookHeadView.h"

#import <AddressBook/AddressBook.h>

#import "MyTapGestureRecognizer.h"

// 需要的协议
@interface ZKingAddressBookViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchResultsUpdating, UIAlertViewDelegate>{
    // 模型与视图
    AddressBookPeopleModel  *_peopleModel;
    AddressBookView         *_addressBookView;
    
    
    // 数据源
    NSArray                 *_array;
    
    NSMutableArray          *_mArray;
    NSMutableDictionary     *_peopleDic;
    
    
    NSMutableArray          *_resultArray;
    NSMutableDictionary     *_newPeopleDic;
}


@property (nonatomic, retain) AddressBookPeopleModel        *peopleModel;// peopel模型
@property (nonatomic, retain) AddressBookView               *addressBookView;// 设置一个通讯的视图

@property (nonatomic, retain) UISearchController            *searchController;

@end

@implementation ZKingAddressBookViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.searchController.searchBar setHidden:NO];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self.searchController.searchBar setHidden:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"通讯录";
    _mArray         = [[NSMutableArray alloc] init];
    _resultArray    = [[NSMutableArray alloc] init];
    _peopleDic      = [[NSMutableDictionary alloc] init];
    _newPeopleDic   = [[NSMutableDictionary alloc] init];
    
    self.addressBookView = [[AddressBookView alloc] init];
    self.view = self.addressBookView;
    
    self.addressBookView.tableView.delegate = self;
    self.addressBookView.tableView.dataSource = self;
    
    // 初始化searchController
    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    _searchController.searchResultsUpdater = self;
    _searchController.searchBar.delegate = self;
    _searchController.dimsBackgroundDuringPresentation = NO;
    _searchController.hidesNavigationBarDuringPresentation = NO;
    _searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    self.addressBookView.tableView.tableHeaderView = self.searchController.searchBar;
    self.searchController.searchBar.placeholder = @"名称、内容";

    

    // 权限请求  异步执行
    ABAddressBookRequestAccessWithCompletion(NULL, ^(bool granted, CFErrorRef error) {
        if (granted) {
            NSLog(@"权限申请成功");
        }else{
            NSLog(@"申请失败");
        }
        
        ABAddressBookRef adRef = ABAddressBookCreateWithOptions(NULL, NULL);
        
        _array = (__bridge NSArray *)ABAddressBookCopyArrayOfAllPeople(adRef);
        
        NSLog(@"%@", _array);
        
        for (int i = 0; i < _array.count; i++) {
            ABRecordRef person = (__bridge ABRecordRef)([_array objectAtIndex:i]);
            
            AddressBookPeopleModel *p = [AddressBookPeopleModel new];
            
            // name
            p.name = (__bridge NSString *)ABRecordCopyCompositeName(person);
            
            // phone
            ABMultiValueRef mref = ABRecordCopyValue(person, kABPersonPhoneProperty);
            p.phone = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(mref, 0));
            
            // photo
            if (ABPersonHasImageData(person)) {
                NSData *imageData = (__bridge NSData *)ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail);
                UIImage *image = [[UIImage alloc] initWithData:imageData];
                p.image = image;
            }
            
            [_mArray addObject:p];
        }
        
        _peopleDic = [self GetDictioanaryWithArray:_mArray];
        
        [self performSelectorOnMainThread:@selector(reloadTable) withObject:nil waitUntilDone:YES];
    });
}

// 判断 字典中有没有以姓名开头的数组 如果没有就创建一个 如果有就将这个p对象添加到对应的数组中
- (NSMutableDictionary *)GetDictioanaryWithArray:(NSMutableArray *)array{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    for (AddressBookPeopleModel *p in array) {
//        NSString *name = [ChineseToPinyin pinyinFromChiniseString:p.name];
        NSString *firstLetter = [p.name substringWithRange:NSMakeRange(0, 1)];
        
        if (![dic objectForKey:firstLetter]) {
            NSMutableArray *arr = [NSMutableArray array];
            [dic setObject:arr forKey:firstLetter];
        }
        
        [[dic objectForKey:firstLetter] addObject:p];
    }
    
    return dic;
}

#pragma mark - reloadTable
- (void)reloadTable{
    [self.addressBookView.tableView reloadData];
}


#pragma mark - 对结果进行过滤
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchString = [self.searchController.searchBar text];
    
    if (_newPeopleDic != nil) {
        [_newPeopleDic removeAllObjects];
        [_resultArray removeAllObjects];
    }
    //过滤数据
    for (AddressBookPeopleModel *p in _mArray) {
        //        hasPrefix 判断一个字符串是否以一个字符串开头  hasSubfix 结尾时候相同
        //        uppercaseString 将所有的字母都转化为大写 [[ChineseToPinyin pinyinFromChiniseString:p.name]
        if ([p.name hasPrefix:[searchString uppercaseString]]) {
            [_resultArray addObject:p];
        }
    }
    _newPeopleDic = [self GetDictioanaryWithArray:_resultArray];
   
    //刷新表格
    [self reloadTable];
}


#pragma mark - tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (!self.searchController.active) {
        return _peopleDic.count;
    }else{
        return _newPeopleDic.count;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (!self.searchController.active) {
        NSArray *sortArray = [_peopleDic.allKeys sortedArrayUsingSelector:@selector(compare:)];
        return [[_peopleDic objectForKey:[sortArray objectAtIndex:section]] count];
    }else{
        NSArray *sortArray = [_newPeopleDic.allKeys sortedArrayUsingSelector:@selector(compare:)];
        return [[_newPeopleDic objectForKey:[sortArray objectAtIndex:section]] count];
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddressBookTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[AddressBookTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    AddressBookPeopleModel *p = nil;
    
    
    if (!self.searchController.active) {
        NSArray *sortArray = [_peopleDic.allKeys sortedArrayUsingSelector:@selector(compare:)];
        NSArray *arr = [_peopleDic objectForKey:[sortArray objectAtIndex:indexPath.section]];
        p = [arr objectAtIndex:indexPath.row];
    }else{
        NSArray *sortArray = [_newPeopleDic.allKeys sortedArrayUsingSelector:@selector(compare:)];
        NSArray *arr = [_newPeopleDic objectForKey:[sortArray objectAtIndex:indexPath.section]];
        p = [arr objectAtIndex:indexPath.row];
    }
    
    cell.peopleNameLabel.text = p.name;
    
    if (p.image) {
        cell.peopleImageView.image = p.image;
    }else{
        cell.peopleImageView.image = [UIImage imageNamed:@"headImage.png"];
    }
    
    // 给send 和 call 添加手势事件
    MyTapGestureRecognizer *sendTap = [[MyTapGestureRecognizer alloc] initWithTarget:self action:@selector(SendViewClicked:)];
    [cell.peopleSendMessageImageView addGestureRecognizer:sendTap];
    sendTap.userInfo = p.phone;
    
    MyTapGestureRecognizer *callTap = [[MyTapGestureRecognizer alloc] initWithTarget:self action:@selector(CallViewClicked:)];
    [cell.peopleCallImageView addGestureRecognizer:callTap];
    callTap.userInfo = p.phone;
    
    return cell;
}

#pragma mark - Send Call
- (void)SendViewClicked:(MyTapGestureRecognizer *)ges{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"tips" message:[NSString stringWithFormat:@"你要给%@发送消息吗", ges.userInfo] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSLog(@"OK 被点击了");
    }];
    [alert addAction:OKAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)CallViewClicked:(MyTapGestureRecognizer *)ges{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"tips" message:[NSString stringWithFormat:@"你要给%@打电话吗", ges.userInfo] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSLog(@"OK 被点击了");
    }];
    [alert addAction:OKAction];
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark - tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 67;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    AddressBookHeadView *headView = [[AddressBookHeadView alloc] init];
    
    NSArray *sortArray = [_peopleDic.allKeys sortedArrayUsingSelector:@selector(compare:)];
    headView.headLabel.text = [sortArray objectAtIndex:section];
    
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 34;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    [searchBar setShowsCancelButton:YES animated:YES];
    
    for (id cc in [searchBar.subviews[0] subviews]) {
        if ([cc isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
